package com.oss.service.oss;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oss.entity.oss.Calendar;
import com.oss.enums.IsDeletedEnum;
import com.oss.mapper.oss.CalendarMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author chengqiang
 */
@Service
public class CalendarService extends ServiceImpl<CalendarMapper, Calendar> {
    /**
     * 获取上一个交易日
     * @param date
     * @return
     */
    public LocalDate getLastTradingDay(LocalDate date){
        LambdaQueryWrapper<Calendar> queryWrapper = new LambdaQueryWrapper<Calendar>();
        queryWrapper.eq(Calendar::getIsDeleted, IsDeletedEnum.NO);
        queryWrapper.eq(Calendar::getIsTradingDay, "tradingday"); // 交易日
        queryWrapper.lt(Calendar::getDate, date);
        queryWrapper.orderByDesc(Calendar::getDate);
        queryWrapper.last("limit 1");
        Calendar calendar = baseMapper.selectOne(queryWrapper);
        if (calendar != null) {
            return calendar.getDate();
        } else {
            throw new RuntimeException("获取last一个交易日失败,原日期="+date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
    }
    /**
     * 获取距离某一日的最近的下一个交易日
     * @param date
     * @return
     */
    public LocalDate getNextTradingDay(LocalDate date){
        LambdaQueryWrapper<Calendar> queryWrapper = new LambdaQueryWrapper<Calendar>();
        queryWrapper.eq(Calendar::getIsDeleted, IsDeletedEnum.NO);
        queryWrapper.eq(Calendar::getIsTradingDay, "tradingday"); // 交易日
        queryWrapper.gt(Calendar::getDate, date);
        queryWrapper.orderByAsc(Calendar::getDate);
        queryWrapper.last("limit 1");
        Calendar calendar = baseMapper.selectOne(queryWrapper);
        if (calendar != null) {
            return calendar.getDate();
        } else {
            throw new RuntimeException("获取next一个交易日失败,原日期="+date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
    }

    /**
     * 查询某一天是否为交易日 , 返回true=是交易日
     * @param today
     * @return
     */
    public boolean isTradeingDay(LocalDate today) {
        LambdaQueryWrapper<Calendar> queryWrapper = new LambdaQueryWrapper<Calendar>();
        queryWrapper.eq(Calendar::getIsDeleted, IsDeletedEnum.NO);
        queryWrapper.eq(Calendar::getIsTradingDay, "tradingday"); // 交易日
        queryWrapper.eq(Calendar::getDate, today);
        long count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
